package com.yaoweigroup.community.ui.bm;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.CApplication;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.NearAdapter;
import com.yaoweigroup.community.adapter.SelectAdapter;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.db.DBUtil;
import com.yaoweigroup.community.enity.Shops;
import com.yaoweigroup.community.enity.TypeIcon;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 列表页面
 * 
 * @author xi
 * 
 */
public class NearListActivity extends Activity implements OnClickListener {

	private PullToRefreshListView shopListView;
	private NearAdapter adapter;
	private List<Shops> list;

	private RelativeLayout left_rl;

	private RelativeLayout type_rl;
	private ListView type_listView;
	private RelativeLayout distance_rl;
	private RelativeLayout prj_rl;
	private RelativeLayout sort_rl;
	private SelectAdapter selectAdapter;
	private List<String> distanceList;
	private List<String> sortList;
	private List<String> prjList;

	private int type = -1;// 0 distance 1 prj 2 sort

	private ObjectMapper mapper;
	private ProgressBar progress;
	private ImageView error_iv;
	private TypeIcon typeIcon;

	private TextView center_tv;
	private boolean isLoadEnd = false;
	private DBUtil dbUtil;
	private TextView distance_tv;
	private TextView prj_tv;
	private TextView sort_tv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_near_list);
		distance_tv = (TextView) findViewById(R.id.distance_tv);
		prj_tv = (TextView) findViewById(R.id.prj_tv);
		sort_tv = (TextView) findViewById(R.id.sort_tv);
		dbUtil = DBUtil.newInstance(this);
		initData();
		mapper = new ObjectMapper();
		selectAdapter = new SelectAdapter(this, distanceList);
		distance_rl = (RelativeLayout) findViewById(R.id.distance_rl);
		distance_rl.setOnClickListener(this);
		prj_rl = (RelativeLayout) findViewById(R.id.prj_rl);
		prj_rl.setOnClickListener(this);
		error_iv = (ImageView) findViewById(R.id.error_iv);
		sort_rl = (RelativeLayout) findViewById(R.id.sort_rl);
		sort_rl.setOnClickListener(this);
		type_listView = (ListView) findViewById(R.id.type_listView);
		type_rl = (RelativeLayout) findViewById(R.id.type_rl);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);
		list = new ArrayList<Shops>();
		progress = (ProgressBar) findViewById(R.id.progress);
		adapter = new NearAdapter(this, list);
		shopListView = (PullToRefreshListView) findViewById(R.id.shopListView);
		type_rl.setOnTouchListener(typeSelectTouchListener);
		shopListView.setAdapter(adapter);
		center_tv = (TextView) findViewById(R.id.center_tv);
		shopListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				int curPosition = position - 1;
				Intent intent = new Intent(NearListActivity.this,
						DetailActivity.class);
				intent.putExtra("detail", list.get(curPosition));
				startActivity(intent);
			}
		});

		shopListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(
						getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);

				progress.setVisibility(View.GONE);
				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				error_iv.setVisibility(View.GONE);
				pageNo = 1;
				list.clear();
				obtainData();
			}
		});

		shopListView
				.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

					@Override
					public void onLastItemVisible() {
						if (isLoadEnd) {
							return;
						}
						error_iv.setVisibility(View.GONE);
						obtainData();
					}
				});

		type_listView.setAdapter(selectAdapter);
		type_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				type_rl.setVisibility(View.GONE);
				if (type == 1) {
					typeIcon = types.get(arg2);
					center_tv.setText(typeIcon.getTypename());
					prj_tv.setText(prjList.get(arg2));
				} else if (type == 2) {
					sort = arg2 + 1;
					sort_tv.setText(sortList.get(arg2));
				} else if (type == 0) {
					distance_tv.setText(distanceList.get(arg2));
					switch (arg2) {
					case 0:
						distance = 1;
						break;
					case 1:
						distance = 4;
						break;
					case 2:
						distance = 10;
						break;
					case 3:
						distance = 200;
						break;
					}
				}
				list.clear();
				pageNo = 1;
				adapter.setDataChange(list);
				progress.setVisibility(View.VISIBLE);
				error_iv.setVisibility(View.GONE);
				obtainData();
			}
		});

		typeIcon = (TypeIcon) getIntent().getSerializableExtra("type");
		if (typeIcon != null) {
			center_tv.setText(typeIcon.getTypename());
		}
		obtainData();
	}

	private List<TypeIcon> types;

	private void initData() {

		distanceList = new ArrayList<String>();
		distanceList.add("1km");
		distanceList.add("4km");
		distanceList.add("10km");
		distanceList.add("不限");

		sortList = new ArrayList<String>();
		sortList.add("默认排序");
		sortList.add("综合评分");
		sortList.add("价格排序");

		prjList = new ArrayList<String>();
		try {
			types = dbUtil.db.findAll(TypeIcon.class);
			if (types != null && types.size() > 0) {

				for (TypeIcon type : types) {
					prjList.add(type.getTypename());
				}
			}
		} catch (DbException e) {
			LogUtil.e("wxf", "DB=" + e.toString());
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.distance_rl:
			if (type == 0 && type_rl.getVisibility() == View.VISIBLE) {
				type_rl.setVisibility(View.GONE);
			} else {
				type_rl.setVisibility(View.VISIBLE);
			}
			type = 0;
			selectAdapter.setDataChange(distanceList);
			break;
		case R.id.prj_rl:
			if (type == 1 && type_rl.getVisibility() == View.VISIBLE) {
				type_rl.setVisibility(View.GONE);
			} else {
				type_rl.setVisibility(View.VISIBLE);
			}
			type = 1;
			selectAdapter.setDataChange(prjList);
			break;
		case R.id.sort_rl:
			if (type == 2 && type_rl.getVisibility() == View.VISIBLE) {
				type_rl.setVisibility(View.GONE);
			} else {
				type_rl.setVisibility(View.VISIBLE);
			}
			type = 2;
			selectAdapter.setDataChange(sortList);
			break;
		}
	}

	OnTouchListener typeSelectTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			type_rl.setVisibility(View.GONE);
			return true;

		}
	};

	private double lat = 31.298487;
	private double lng = 121.164426;
	private int pageSize = 10;
	private int pageNo = 1;
	private int sort = 1;
	private int distance = 40;

	/**
	 * 获取数据
	 */
	private void obtainData() {
		if (CApplication.latLng != null) {
			lat = CApplication.latLng.latitude;
			lng = CApplication.latLng.longitude;
		}
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		if (typeIcon != null) {
			jsonUtil.add("typeid", typeIcon.getTypeid());
		}

		jsonUtil.add("lat", lat);
		jsonUtil.add("lng", lng);
		jsonUtil.add("distance", distance);
		jsonUtil.add("sort", sort);
		jsonUtil.add("pageNo", pageNo);
		jsonUtil.add("pageSize", pageSize);

		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getShops, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								nears = mapper.readValue(data,
										new TypeReference<List<Shops>>() {
										});
								handler.sendEmptyMessage(NEAR_SUCCESS);
							} else {
								handler.sendEmptyMessage(NEAR_FAIL);
							}
						} catch (Exception e) {
							handler.sendEmptyMessage(NEAR_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(NEAR_FAIL);

					}

				});
	}

	private List<Shops> nears;
	public final int NEAR_SUCCESS = 0x2210;
	public final int NEAR_FAIL = NEAR_SUCCESS + 1;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			progress.setVisibility(View.GONE);
			switch (msg.what) {
			case NEAR_SUCCESS:
				if (nears != null && nears.size() > 0) {
					list.addAll(nears);
					if (nears.size() < pageSize) {
						isLoadEnd = true;
					} else {
						pageNo += 1;
						isLoadEnd = false;
					}
				} else {
					if (list.size() == 0) {
						error_iv.setVisibility(View.VISIBLE);
						Toast.makeText(NearListActivity.this, "附近暂无商家数据", 500)
								.show();
					}
				}
				shopListView.onRefreshComplete();
				adapter.setDataChange(list);

				break;
			case NEAR_FAIL:
				error_iv.setVisibility(View.VISIBLE);
				break;
			}
		};
	};
}
